<template>
  <el-upload
      ref="uploadRef"
      class="avatar-uploader"
      :action="uploadUrl"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :headers="headers"
  >
  </el-upload>
</template>

<script lang="ts" setup>
import {ref, computed, watch, defineExpose} from 'vue'
import {ElMessage} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import type {UploadProps} from 'element-plus'
import {API_BASE_URL} from '@/config/index.js'
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:modelValue'])

// 用于预览的URL
const previewUrl = ref('')

// 监听modelValue变化，更新预览图
watch(() => props.modelValue, (newValue) => {
  previewUrl.value = newValue
}, {immediate: true})

// 上传地址
const uploadUrl = computed(() => {

  // return import.meta.env.VITE_API_URL + '/api/system/ufr/upload/facePic'
  return API_BASE_URL + '/api/system/ufr/upload/facePic'
})
const token = localStorage.getItem('geeker-user')
const token2 = 'eyJhbGciOiJIUzUxMiJ9.eyJwY19sb2dpbl91c2VyX2tleSI6IjQ0NmFlNjk3NDllZDQ0MTU4OTczNzY1ODlmMDVmZjA3In0.t5lcfagqe4f5_YGOCoS7Fj2LtSTT3i660L-XNnQ44UEvuoswYrNcMP337npZ9XbzBDMIA5k3Yxgs5demuw18yA'

// 请求头
const headers = ref({
  // 如需添加token等认证信息
  'Authorization': `Bearer ${token || token2}` // 使用本地存储的token作为Authorization头部
})

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response
) => {
  if (response && response.code === 200) {
    // 假设后端返回的数据格式为 {code: 200, data: {url: 'image_url'}} 或 {code: 200, data: 'image_url'}
    const imageUrl = response.rows || ''
    console.log(API_BASE_URL + imageUrl)
    previewUrl.value = imageUrl
    emit('update:modelValue', API_BASE_URL+imageUrl)
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error('头像上传失败: ' + (response.msg || '未知错误'))
  }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // 允许多种图片格式
  const isImage = ['image/jpeg', 'image/png', 'image/gif'].includes(rawFile.type)
  const isLt2M = rawFile.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('头像必须是JPG/PNG/GIF格式!')
    return false
  } else if (!isLt2M) {
    ElMessage.error('头像大小不能超过2MB!')
    return false
  }
  return true
}

// 添加上传组件的引用
const uploadRef = ref()

// 暴露触发上传的方法
const openUpload = () => {
  // 修正：通过查找和触发隐藏的input元素来打开文件选择器
  const inputEl = uploadRef.value?.$el.querySelector('input[type="file"]')
  if (inputEl) {
    inputEl.click()
  } else {
    console.error('找不到上传输入元素')
  }
}

// 暴露方法供父组件调用
defineExpose({
  openUpload
})
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
